<template>
  <div>
    <el-tree :data="data"
             :props="defaultProps"
             :expand-on-click-node="false"
             show-checkbox
             node-key="catId"
             :default-expanded-keys="this.expandedKey"
             @node-drop="handleDrop"
             draggable
             :allow-drop="allowDrop"
    >
    <span class="custom-tree-node" slot-scope="{ node, data }">
        <span>{{ node.label }}</span>
        <span>
          <el-button
            type="text"
            size="mini"
            @click="() => append(data)"
            v-if="data.catLevel <= 2"
          >
            Append
          </el-button>
          <el-button
            type="text"
            size="mini"
            @click="() => edit(data)"
          >
            Edit
          </el-button>
          <el-button
            type="text"
            size="mini"
            @click="() => remove(node, data)"
            v-if="data.children.length === 0"
          >
            Delete
          </el-button>
        </span>
      </span>
    </el-tree>

    <el-dialog :title="title" :visible.sync="dialogVisible" :close-on-click-modal="false">
      <el-form :model="category">
        <el-form-item label="分类名称"
                      :rules="[
      { required: true, message: '请输入分类名称', trigger: ['blur', 'change'] },
    ]"
        >
          <el-input v-model="category.name" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="图标">
          <el-input v-model="category.icon" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="单位">
          <el-input v-model="category.productUnit" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitData">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
export default {
  data () {
    return {
      pCid: [],
      updateNodes: [],
      maxNodeLevel: 0,
      title: '',
      dialogType: '',
      data: [],
      category: {
        name: '',
        parentCid: 0,
        showStatus: 1,
        sort: 0,
        catLevel: 2,
        catId: null,
        icon: null,
        productUnit: ''
      },
      expandedKey: [],
      dialogVisible: false,
      defaultProps: {
        children: 'children',
        label: 'name'
      }
    }
  },
  created () {
    this.getMenus()
  },
  methods: {
    handleDrop (draggingNode, dropNode, dropType, ev) {
      console.log('handleDrop: ', draggingNode, dropNode, dropType)
      // 1、当前节点最新的父节点id
      let pCid = 0
      let siblings = null
      if (dropType === 'before' || dropType === 'after') {
        pCid =
          dropNode.parent.data.catId === undefined
            ? 0
            : dropNode.parent.data.catId
        siblings = dropNode.parent.childNodes
      } else {
        pCid = dropNode.data.catId
        siblings = dropNode.childNodes
      }
      this.pCid.push(pCid)

      // 2、当前拖拽节点的最新顺序，
      for (let i = 0; i < siblings.length; i++) {
        if (siblings[i].data.catId === draggingNode.data.catId) {
          let catLevel = draggingNode.level
          if (siblings[i].level !== draggingNode.level) {
            catLevel = siblings[i].level
            this.updateChildNodeLevel(siblings[i])
          }
          this.updateNodes.push({
            catId: siblings[i].data.catId,
            sort: i,
            parentCid: pCid,
            catLevel: catLevel
          })
        } else {
          this.updateNodes.push({ catId: siblings[i].data.catId, sort: i })
        }
      }
      console.log('updateNodes', this.updateNodes)
    },
    updateChildNodeLevel (node) {
      if (node.childNodes.length > 0) {
        for (let i = 0; i < node.childNodes.length; i++) {
          var cNode = node.childNodes[i].data
          this.updateNodes.push({
            catId: cNode.catId,
            catLevel: node.childNodes[i].level
          })
          this.updateChildNodeLevel(node.childNodes[i])
        }
      }
    },
    countNodeLevel (node) {
      if (node.children != null && node.children.length > 0) {
        for (let i = 0; i < node.children.length; i++) {
          if (node.children[i].catLevel > this.maxNodeLevel) {
            this.maxNodeLevel = node.children[i].catLevel
          }
          this.countNodeLevel(node.children[i])
        }
      }
    },
    allowDrop (draggingNode, dropNode, type) {
      this.countNodeLevel(draggingNode.data)
      var deep = this.maxNodeLevel - draggingNode.data.catLevel + 1
      if (type === 'inner') {
        return (deep + dropNode.level) <= 3
      } else {
        return (deep + dropNode.parent.level) <= 3
      }
    },
    submitData () {
      if (this.dialogType === 'add') {
        this.addCategory()
      } else {
        this.editCategory()
      }
    },
    edit (data) {
      this.dialogType = 'edit'
      this.title = '修改'
      this.dialogVisible = true
      this.$http({
        method: 'get',
        url: this.$http.adornUrl('/product/category/info/' + data.catId)
      }).then(({data}) => {
        console.log('accept')
        console.log(data.data)
        this.category.name = data.data.name
        this.category.catId = data.data.catId
        this.category.icon = data.data.icon
        this.category.productUnit = data.data.productUnit
        this.category.parentCid = data.data.parentCid
      })
    },
    editCategory () {
      var { catId, name, icon, productUnit } = this.category
      var data = {catId: catId, name: name, icon: icon, productUnit: productUnit}
      this.$http({
        method: 'post',
        url: this.$http.adornUrl('/product/category/update'),
        data: this.$http.adornData(data, false)
      }).then(({data}) => {
        this.getMenus()
        this.dialogVisible = false
        this.expandedKey = [this.category.parentCid]
        this.$message({
          message: '操作成功',
          type: 'success',
          duration: 1500
        })
      })
      console.log(1)
    },
    addCategory () {
      var pa = this.category.parentCid
      console.log(this.category)
      this.$http({
        url: this.$http.adornUrl('/product/category/save'),
        method: 'post',
        data: this.$http.adornData(this.category, false)
      }).then(data => {
        this.getMenus()
        this.expandedKey = [pa]
        this.$message({
          message: '操作成功',
          type: 'success',
          duration: 1500
        })
      })
      this.dialogVisible = false
    },
    append (data) {
      this.dialogType = 'add'
      this.title = '添加'
      this.category.name = ''
      this.category.catId = null
      this.category.icon = null
      this.category.productUnit = ''
      this.dialogVisible = true
      this.category.parentCid = data.catId
      this.category.catLevel = data.catLevel * 1 + 1
      console.log(data)
    },
    remove (data) {
      var ids = [data.data.catId]
      var pa = data.data.parentCid
      this.$confirm(`确定进行删除操作?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http({
          url: this.$http.adornUrl('/product/category/delete'),
          method: 'post',
          data: this.$http.adornData(ids, false)
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.getMenus()
            this.expandedKey = [pa]
            this.$message({
              message: '操作成功',
              type: 'success',
              duration: 1500
            })
          } else {
            this.$message.error(data.msg)
          }
        })
      }).catch(() => {})
    },
    getMenus () {
      this.$http({
        url: this.$http.adornUrl(`/product/category/list`),
        method: 'get'
      }).then(res => {
        this.data = res.data.page.list
      })
    }
  }
}
</script>

<style scoped>

</style>
